package 可视化算法.概率模拟算法.分钱游戏;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.util.Arrays;

/**
 * @author MT
 * 算法可视化中的MVC
 * @date 2019-11-29 10:03
 */
public class AlgoVisualizer {

    // 动画时间间隔
    private static int DELAY = 40;
    private int[] money;
    private AlgoFrame frame;


    public AlgoVisualizer(int sceneWidth, int sceneHeight) {
        money = new int[100];
        for (int i = 0; i < money.length; i++) {
            money[i] = 100;
        }
        EventQueue.invokeLater(() -> {
            this.frame = new AlgoFrame("分钱游戏", sceneWidth, sceneHeight);
            // 添加键盘事件
            this.frame.addKeyListener(new AlgoKeyListener());
            // 添加鼠标事件
            this.frame.addMouseListener(new AlgoMouseListener());
            new Thread(() -> {
                this.run();
            }).start();
        });
    }

    /**
     * 动画逻辑
     */
    private void run() {
        while (true) {
            // 排序money数组
            Arrays.sort(money);

            frame.render(money);
            AlgoVisHelper.pause(DELAY);

            // 加快50倍速度
            for (int k = 0; k < 50; k++) {

                for (int i = 0; i < money.length; i++) {

                    int j = (int) (Math.random() * money.length);
                    money[i] -= 1;
                    money[j] += 1;
                }
            }
        }
    }


    private class AlgoKeyListener extends KeyAdapter {
    }

    private class AlgoMouseListener extends MouseAdapter {
    }
}
